package com.group.controller;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.base.view.BaseResult;
import com.base.view.GeneralResult;
import com.base.view.ListResult;
import com.group.model.*;
import com.group.service.BookScheduleService;
import com.group.util.NoteException;
import com.group.view.BookBonusView;

/**
 * 小说相关接口
 * 
 * @author zhaolei
 *
 */
@Controller
public class BookController extends BaseController {

	@Autowired
	BookScheduleService bookScheduleService;

	/**
	 * 添加阅读记录
	 * @param logs logs
	 * @return BaseResult
	 */
	@PostMapping("/book/readlog/add")
	@ResponseBody
	public BaseResult addReadLog(@RequestBody BookReadLog[] logs) {
		User user = beanDao.quickQueryOne(User.class, "readerId", logs[0].getReaderId());
		for (BookReadLog log : logs) {
			BookReadLog para = new BookReadLog();
			para.setReaderId(log.getReaderId());
			para.setCapture(log.getCapture());
			para.setName(log.getName());
			if (beanDao.queryOne(para) != null)
				continue;

			if (user != null)
				log.setUserId(user.getId());

			beanDao.save(log);
		}

		return new BaseResult();
	}

	/**
	 * 绑定用户的readerId
	 * 
	 * @param userId 用户id
	 * @param readerId 阅读id
	 * @return BaseResult
	 */
	@GetMapping("/book/user/bind")
	@ResponseBody
	public BaseResult bindUser(Long userId, String readerId) {
		if (readerId == null || !readerId.contains("-")) {
			throw new NoteException("读者id不合法");
		}

		if (beanDao.quickQueryOne(User.class, "readerId", readerId) != null)
			throw new NoteException("readerId 已经绑定过");

		User user = new User();
		user.setId(userId);
		user.setReaderId(readerId);
		beanDao.save(user);

		bookDao.updateReadLogUser(readerId, userId);
		return new BaseResult();
	}

	/**
	 * 添加小说
	 * 
	 * @param book 小说
	 * @return BaseResult
	 */
	@PostMapping("/book/add")
	@ResponseBody
	public BaseResult addBook(@RequestBody Book book) {
		beanDao.save(book);
		return new BaseResult();
	}

	/**
	 * 删除小说
	 * 
	 * @param bookId 小说id
	 * @return BaseResult
	 */
	@DeleteMapping("/book/delete")
	@ResponseBody
	public BaseResult deleteBook(Long bookId) {
		beanDao.quickDelete(Book.class, "id", bookId);

		return new BaseResult();
	}

	/**
	 * 查询小说列表
	 * 
	 * @param name 书名
	 * @param type 类型
	 * @param start 开始
	 * @param limit 条数
	 * @return ListResult<Book>
	 */
	@GetMapping("/book/query")
	@ResponseBody
	public ListResult<Book> queryBook(String name, Integer start, Integer limit,int type) {

		return new ListResult<Book>().setList(bookDao.queryBook(name, start, limit,type)).setTotal(bookDao.queryBookCount(name,type));
	}

	/**
	 * 修改小说年华收益率和起头限额
	 * @param investmentQuota 年化
	 * @param profit 投资
	 * @param bookId 小说id
	 */
	@GetMapping("/book/update")
	@ResponseBody
	public void updateBook(int investmentQuota,double profit,Long bookId) {
		bookDao.updateBook(investmentQuota, profit,bookId);
	}

	/**
	 * 上下架小说
	 *
	 * @param bookId 小说id
	 * @param state 状态
	 * @return String
	 */
	@GetMapping("/book/upperAndLowerShelves")
	@ResponseBody
	public GeneralResult<String> upperAndLowerShelves(Long bookId,int state) {
		double totalInvest = bookDao.countBookTotalInvest(bookId);
		if (totalInvest > 0 && state == 0) {
			return new GeneralResult<String>().setValue("该小说已下架或不能下架");
		}else{
			bookDao.updateBookState(bookId, state);
		}
		return new GeneralResult<String>().setValue("成功");
	}

	/**
	 * 投资小说
	 * 
	 * @param log BookInvestLog
	 * @param request HttpServletRequest
	 * @return BaseResult
	 */
	@PostMapping("/book/invest")
	@ResponseBody
	public synchronized BaseResult investBook(@RequestBody BookInvestLog log, HttpServletRequest request) {
		if (log.getInvestMonth() == null)
			throw new NoteException("投资时间不能为空");
		if (log.getName() == null)
			throw new NoteException("书名不能为空");
		if (!(log.getInvestMonth() == 3 || log.getInvestMonth() == 6 || log.getInvestMonth() == 12))
			throw new NoteException("投资时间不合法");

		log.init();

		// 验证余额是否足够
		UserTicker ut = tickerService.getUserTicker(log.getUserId(), "wecc");

		if (ut.getNum() < log.getAmount())
			throw new NoteException("用户余额不足");

		beanDao.save(log);

		// 扣除币
		tickerService.addTicker(log.getUserId(), "wecc", -log.getAmount(), "投资小说");

		return new BaseResult();
	}

	/**
	 * 每日分红排行榜
	 * @return  UserTickerLog
	 */
	@GetMapping("/book/bonus/rank")
	@ResponseBody
	public ListResult<UserTickerLog> queryBonusRank() {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		List<UserTickerLog> logs = bookDao.queryBonusRank(cal.getTime());
		for (UserTickerLog log : logs) {
			log.setUserHeadimage(beanDao.quickQueryOneById(User.class, log.getUserId()).getHeadimage());
		}

		return new ListResult<UserTickerLog>().setList(logs);
	}

	/**
	 * 查询投资记录
	 * @param userId 用户id
	 * @param start 开始
	 * @param limit 条数
	 * @param date 时间
	 * @param type 类型
	 * @return BookInvestLog
	 */
	@GetMapping("/book/invest/my")
	@ResponseBody
	public ListResult<BookInvestLog> queryMyBookInvestLog(Long userId, Integer start, Integer limit,String date,int type) {
		validPage(start, limit);
		List<BookInvestLog> logs = bookDao.queryBookInvestLog(userId, start, limit,date,type);
   /*for (BookInvestLog log : logs) {
      log.setBook(beanDao.quickQueryOneById(Book.class, log.getBookId()));
   }*/
		return new ListResult<BookInvestLog>().setList(logs).setTotal(bookDao.queryBookInvestLogCount(userId,date,type)).setOther(bookDao.queryBookInvestAmountCount(userId,date,type));
	}

	/**
	 * 查询投资记录详细
	 * @param userId 用户id
	 * @param start 开始
	 * @param limit 条数
	 * @param userName 用户名称
	 * @param date 时间
	 * @param type 类型
	 * @return BookInvestLog
	 */
	@GetMapping("/book/invest/mydetail")
	@ResponseBody
	public ListResult<BookInvestLog> queryMyBookInvestLogDetail(Long userId, Integer start, Integer limit,String userName,String date,int type) {
		validPage(start, limit);
		List<BookInvestLog> logs = bookDao.queryBookInvestLogDetail(userId, start, limit,userName,date,type);

		/*for (BookInvestLog log : logs) {
			log.setBook(beanDao.quickQueryOneById(Book.class, log.getBookId()));
		}*/
		return new ListResult<BookInvestLog>().setList(logs).setTotal(bookDao.queryBookInvestLogCounts(userId,userName,date,type));
	}

	/**
	 * 查询我的总分红,昨日分红
	 * 
	 * @param userId 用户id
	 * @param type 类型
	 * @return  BookBonusView
	 */
	@GetMapping("/book/bonus/my")
	@ResponseBody
	public GeneralResult<BookBonusView> queryBookBonusView(Long userId,int type) {
		BookBonusView view = new BookBonusView();
		Timestamp d = new Timestamp(System.currentTimeMillis());
		String date = d.toString().substring(0,10);
		view.setYesterdayBonus(bookDao.queryYestodayBonus(userId,date,type));
		view.setTotalBonus(bookDao.queryTotalBonus(userId,type));

		return new GeneralResult<BookBonusView>().setValue(view);
	}

	private volatile int orderNum = 1;
	/**
	 * 抓取数据完成后 完成统计信息
	 * 
	 * @return BaseResult
	 */
	@GetMapping("/book/statistic")
	@ResponseBody
	public BaseResult test() {
//		bookScheduleService.handleGetTokenEveryday();
		bookScheduleService.handleBookStatistic();
		return new BaseResult();
	}

	@GetMapping("/book/statistics")
	@ResponseBody
	public BaseResult tests() {
		bookScheduleService.handleUserTicker();
		bookScheduleService.handExpireInvest();
		return new BaseResult();
	}

	@GetMapping("/book/test1")
	@ResponseBody
	public BaseResult test1() {
//		bookScheduleService.handleBookStatistic();
		return new BaseResult();
	}
}
